package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.bean.search.rule.RuleHelper;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.base.bean.BaseEnum;
import com.fz.us.oa.core.entity.com.Person;
import com.fz.us.oa.core.service.com.PersonService;
import com.fz.us.oa.core.service.com.ResidentService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dzw on 2018/4/16.
 * 情况明细表 筛选条件之后导出excel
 */
@Controller
@RequestMapping(value = "/com/screen")
public class ScreenController extends BaseController {
    private static final long serialVersionUID = 5358758889639099170L;

    @Autowired
    private PersonService personService;
    @Autowired
    private ResidentService residentService;

    /**
     * 进入页面
     */
    @RequestMapping(value = "toPage", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String toPage(@CurrentUser User user, Model model, String type){
        List<DictItem> streetList = getDictItems(user, "street");
        List<DictItem> eduList = getDictItems(user, "edu");
        List<DictItem> personNatureList = getDictItems(user, "personNature");
        List<DictItem> nationList = getDictItems(user, "nation");
        model.addAttribute("streetList", streetList);
        model.addAttribute("eduList", eduList);
        model.addAttribute("personNatureList", personNatureList);
        model.addAttribute("nationList", nationList);
        model.addAttribute("type", type);
        return "/com/screen";
    }

    /**
     * 获取最后的结果list
     */
    public List<Person> getPersonList(String type, String streetId, String gender, String birthdayStart, String birthdayEnd, Integer ageStart,
                                      Integer ageEnd, String eduId, String joinPartyStart, String joinPartyEnd, String joinWorkStart,
                                      String joinWorkEnd, String personNatureId, Integer isFanPin, Integer shoulder, String nationId){
        Order order = Order.order("createTime", SearchEnum.OrderType.asc);
        List<Rule> rules = new ArrayList<Rule>();
        rules.add(RuleHelper.eq("state", BaseEnum.StateEnum.Enable));
        rules.add(RuleHelper.ne("personNature", getShuJiHouBei()));

        if("before".equals(type)){
            rules.add(RuleHelper.eq("generalDict", getGeneralBefore()));
        }else{
            rules.add(RuleHelper.eq("generalDict", getGeneralAfter()));
        }

        if(StringUtils.isNotEmpty(streetId)){
            rules.add(RuleHelper.in("street.id", streetId.split(",")));
        }

        if(StringUtils.isNotEmpty(gender)){
            rules.add(RuleHelper.eq("gender", gender));
        }

        if(StringUtils.isNotEmpty(birthdayStart)){
            rules.add(RuleHelper.ge("birthday", DataUtil.StringToDate(birthdayStart, "yyyy-MM-dd")));
        }

        if(StringUtils.isNotEmpty(birthdayEnd)){
            rules.add(RuleHelper.le("birthday", DataUtil.StringToDate(birthdayEnd, "yyyy-MM-dd")));
        }

        if(StringUtils.isNotEmpty(eduId)){
            rules.add(RuleHelper.in("highEdu.id", eduId.split(",")));
        }

        if(StringUtils.isNotEmpty(joinPartyStart)){
            rules.add(RuleHelper.ge("joinPartyDate", DataUtil.StringToDate(joinPartyStart)));
        }

        if(StringUtils.isNotEmpty(joinPartyEnd)){
            rules.add(RuleHelper.le("joinPartyDate", DataUtil.StringToDate(joinPartyEnd)));
        }

        if(StringUtils.isNotEmpty(joinWorkStart)){
            rules.add(RuleHelper.ge("joinWorkDate", DataUtil.StringToDate(joinWorkStart)));
        }

        if(StringUtils.isNotEmpty(joinWorkEnd)){
            rules.add(RuleHelper.le("joinWorkDate", DataUtil.StringToDate(joinWorkEnd)));
        }

        if(StringUtils.isNotEmpty(personNatureId)){
            rules.add(RuleHelper.in("personNature.id", personNatureId.split(",")));
        }

        if(isFanPin!=null){
            if(isFanPin==1){
                rules.add(RuleHelper.eq("personNature.name", "退休返聘"));
            }else{
                rules.add(RuleHelper.ne("personNature.name", "退休返聘"));
            }
        }

        if(shoulder!=null){
            rules.add(RuleHelper.eq("shoulder", shoulder));
        }

        if(StringUtils.isNotEmpty(nationId)){
            rules.add(RuleHelper.eq("nation", dictItemService.get(nationId)));
        }

        SearchResultPaging searchResult = personService.paging(null, rules, order, "com.fz.us.oa.core.entity.com.Person",
                new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed}, null);
        List<Person> ageList = searchResult.getList();


        if(ageStart!=null || ageEnd!=null){
            List<Person> personList = new ArrayList<Person>();
            for(Person person:ageList){
                int age = getAge(person.getBirthday());
                if(ageStart!=null && age<ageStart){
                    continue;
                }

                if(ageEnd!=null && age>ageEnd){
                    continue;
                }
                personList.add(person);
            }
            return personList;
        }else{
            return ageList;
        }
    }

    /**
     * 验证最终list是否为空
     */
    @RequestMapping(value = "checkList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object checkList(String type, String streetId, String gender, String birthdayStart, String birthdayEnd, Integer ageStart,
                            Integer ageEnd, String eduId, String joinPartyStart, String joinPartyEnd, String joinWorkStart,
                            String joinWorkEnd, String personNatureId, Integer isFanPin, Integer shoulder, String nationId){
        List<Person> personList = getPersonList(type,streetId,gender,birthdayStart,birthdayEnd,ageStart,ageEnd,eduId,joinPartyStart,joinPartyEnd,joinWorkStart,joinWorkEnd,personNatureId,isFanPin,shoulder,nationId);
        if(personList.size()>0){
            return ajaxJson(resultService.success("找到了"+personList.size()+"名人员"));
        }else{
            return ajaxJson(resultService.fail("没有找到符合条件的人员"));
        }
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public Object export(@CurrentUser User user, String type, String title, String filepath, String fileFullName, String streetId,
                         String gender, String birthdayStart, String birthdayEnd, Integer ageStart, Integer ageEnd, String eduId, String joinPartyStart,
                         String joinPartyEnd, String joinWorkStart, String joinWorkEnd, String personNatureId, Integer isFanPin, Integer shoulder,
                         String nationId) throws IOException {
        List<Person> personList = getPersonList(type,streetId,gender,birthdayStart,birthdayEnd,ageStart,ageEnd,eduId,joinPartyStart,joinPartyEnd,joinWorkStart,joinWorkEnd,personNatureId,isFanPin,shoulder,nationId);

        if(personList.size()==0){
            return ajaxJson(resultService.fail("没有找到符合条件的人员"));
        }

        String name = "2018年换届书记情况明细表.xls";
        if("before".equals(type)){
            name = "2018年换届前书记情况明细表.xls";
        }else if("after".equals(type)){
            name = "2018年换届后书记情况明细表.xls";
        }

        File file=new File(URLDecoder.decode(filepath, "UTF-8"));
        String fileName = URLDecoder.decode(fileFullName, "UTF-8");
        OutputStream outputStream = null;
        InputStream inputStream = new FileInputStream(file);
        Workbook workbook = new HSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheetAt(0); //获取第一张sheet

        CellStyle style = workbook.createCellStyle();
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//垂直
        style.setAlignment(CellStyle.ALIGN_CENTER);//水平

        Row row1 = sheet.getRow(0);
        row1.getCell(0).setCellValue(title); //设置标题

        for(int i=0;i<personList.size();i++){
            Person person = personList.get(i);
            Row row = sheet.createRow(i + 2); //有两行标题
            row.setHeight((short) 500);
            Cell cell0 = row.createCell(0);
            cell0.setCellStyle(style);
            cell0.setCellValue(i + 1);

            Cell cell1 = row.createCell(1);
            cell1.setCellValue(StringUtils.isNotEmpty(person.getName()) ? person.getName() : "");
            cell1.setCellStyle(style);

            Cell cell2 = row.createCell(2);
            cell2.setCellValue(person.getStreet() != null ? person.getStreet().getName() : "");
            cell2.setCellStyle(style);

            Cell cell3 = row.createCell(3);
            cell3.setCellValue(person.getResident() != null ? person.getResident().getName() : "");
            cell3.setCellStyle(style);

            Cell cell4 = row.createCell(4);
            cell4.setCellValue(StringUtils.isNotEmpty(person.getGender()) ? person.getGender() : "");
            cell4.setCellStyle(style);

            Cell cell5 = row.createCell(5);
            cell5.setCellValue(StringUtils.isNotEmpty(person.getCardId()) ? person.getCardId() : "");
            cell5.setCellStyle(style);

            Cell cell6 = row.createCell(6);
            cell6.setCellValue(person.getBirthday() != null ? DataUtil.DateToString(person.getBirthday(),"yyyy-MM"):"");
            cell6.setCellStyle(style);

            Cell cell7 = row.createCell(7);
            cell7.setCellValue(getAge(person.getBirthday()));
            cell7.setCellStyle(style);

            Cell cell8 = row.createCell(8);
            cell8.setCellValue(person.getHighEdu() != null ? person.getHighEdu().getName() : "");
            cell8.setCellStyle(style);

            Cell cell9 = row.createCell(9);
            cell9.setCellValue(person.getJoinPartyDate() != null ? DataUtil.DateToString(person.getJoinPartyDate(), "yyyy-MM"):"");
            cell9.setCellStyle(style);

            Cell cell10 = row.createCell(10);
            cell10.setCellValue(person.getJoinWorkDate() != null ? DataUtil.DateToString(person.getJoinWorkDate(),"yyyy-MM"):"");
            cell10.setCellStyle(style);

            Cell cell11 = row.createCell(11);
            cell11.setCellValue(person.getPersonNature() != null ? person.getPersonNature().getName() : "");
            cell11.setCellStyle(style);

            Cell cell12 = row.createCell(12);
            cell12.setCellStyle(style);
            if(person.getPersonNature()!=null){
                cell12.setCellValue("退休返聘".equals(person.getPersonNature().getName()) ? "是" : "否");
            }else{
                cell12.setCellValue("否");
            }

            Cell cell13 = row.createCell(13);
            cell13.setCellValue(person.getShoulder()==1?"是":"否");
            cell13.setCellStyle(style);

            Cell cell14 = row.createCell(14);
            cell14.setCellValue(person.getNation() != null ? person.getNation().getName():"");
            cell14.setCellStyle(style);
        }

        try {
            outputStream = new FileOutputStream(fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            workbook.write(outputStream);
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        File file2=new File(URLDecoder.decode(fileName, "UTF-8"));
        HttpHeaders headers = new HttpHeaders();
        fileName = new String(name.getBytes("UTF-8"), "ISO8859-1");
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file2),
                headers, HttpStatus.CREATED);
    }
}
